<template>
  <div class="counselor-review">
    <el-card class="review-card">
      <template #header>
        <div class="card-header">
          <span>咨询师审核</span>
          <el-radio-group v-model="filterStatus" @change="handleFilterChange">
            <el-radio-button label="PENDING">待审核</el-radio-button>
            <el-radio-button label="APPROVED">已通过</el-radio-button>
            <el-radio-button label="REJECTED">已拒绝</el-radio-button>
          </el-radio-group>
        </div>
      </template>

      <el-table 
        v-loading="loading"
        :data="counselorList" 
        style="width: 100%"
      >
        <el-table-column prop="realName" label="姓名" />
        <el-table-column prop="title" label="职称" />
        <el-table-column prop="workYears" label="从业年限" />
        <el-table-column label="证书" width="100">
          <template #default="scope">
            <el-button 
              type="primary" 
              link 
              @click="previewCertificate(scope.row)"
            >
              查看证书
            </el-button>
          </template>
        </el-table-column>
        <el-table-column 
          prop="introduction" 
          label="个人介绍" 
          show-overflow-tooltip 
        />
        <el-table-column 
          prop="createTime" 
          label="申请时间" 
          width="160"
          :formatter="formatCreateTime"
        />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <template v-if="scope.row.status === STATUS.PENDING">
              <el-button
                type="success"
                link
                @click="handleReview(scope.row, STATUS.APPROVED)"
              >
                通过
              </el-button>
              <el-button
                type="danger"
                link
                @click="handleReview(scope.row, STATUS.REJECTED)"
              >
                拒绝
              </el-button>
            </template>
            <template v-else>
              <el-tag
                :type="scope.row.status === STATUS.APPROVED ? 'success' : 'danger'"
              >
                {{ getStatusText(scope.row.status) }}
              </el-tag>
              <el-button
                v-if="scope.row.status === STATUS.REJECTED"
                type="primary"
                link
                @click="showRejectReason(scope.row)"
              >
                查看原因
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="counselorList.length"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPendingCounselors, reviewCounselor } from '@/api/counselor'
import type { CounselorVO } from '@/types/counseling'
import { formatTime } from '@/utils/time'

// 添加类型声明
interface TableRow {
  createTime: string
  [key: string]: any
}

// 格式化创建时间
const formatCreateTime = (row: TableRow) => {
  return formatTime(row.createTime)
}

const counselorList = ref<CounselorVO[]>([])
const loading = ref(false)
const filterStatus = ref('PENDING')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 状态常量
const STATUS = {
  PENDING: 'PENDING',
  APPROVED: 'APPROVED',
  REJECTED: 'REJECTED'
} as const

// 状态显示映射
const statusMap: Record<string, string> = {
  [STATUS.PENDING]: '待审核',
  [STATUS.APPROVED]: '已通过',
  [STATUS.REJECTED]: '已拒绝'
}

// 获取咨询师列表
const fetchCounselorList = async () => {
  try {
    loading.value = true
    const res = await getPendingCounselors({
      status: filterStatus.value,
      current: currentPage.value,
      size: pageSize.value
    })
    counselorList.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    console.error('获取咨询师列表失败:', error)
    ElMessage.error('获取列表失败')
  } finally {
    loading.value = false
  }
}

// 预览证书
const previewCertificate = (row: CounselorVO) => {
  if (row.certificateUrl) {
    window.open( row.certificateUrl, '_blank')
  } else {
    ElMessage.warning('未上传证书')
  }
}

// 审核处理
const handleReview = async (row: CounselorVO, status: string) => {
  try {
    let reviewNote = ''
    if (status === STATUS.REJECTED) {
      const { value } = await ElMessageBox.prompt('请输入拒绝原因', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (value) => {
          if (!value) {
            return '请输入拒绝原因'
          }
          return true
        }
      })
      reviewNote = value
    }

    await reviewCounselor({
      id: row.id,
      status,
      reviewNote
    })

    ElMessage.success('审核操作成功')
    fetchCounselorList()
  } catch (error) {
    console.error('审核失败:', error)
    ElMessage.error('审核失败')
  }
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchCounselorList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchCounselorList()
}

const handleFilterChange = () => {
  currentPage.value = 1
  fetchCounselorList()
}

// 获取状态显示文本
const getStatusText = (status: string | null | undefined): string => {
  if (!status) return '未知状态'
  return statusMap[status] || status
}

// 查看拒绝原因
const showRejectReason = (row: CounselorVO) => {
  ElMessageBox.alert(row.reviewNote || '无', '拒绝原因', {
    confirmButtonText: '确定'
  })
}

onMounted(() => {
  fetchCounselorList()
})
</script>

<style lang="scss" scoped>
.counselor-review {
  padding: 20px;

  .review-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 